<template>
  <div style="height: 100%;overflow: auto;background: white">
    <el-row :gutter="5" style="height: auto;max-width: 1946px;min-width:1100px;overflow: auto;padding: 5px;">
      <el-col :span="13">
        <el-card class="box-card1" shadow="never">
          <div slot="header" class="clearfix">
            <i class="el-icon-user-solid icon"></i><span>用户信息</span>
            <!-- <el-button style="float: right; padding: 3px 0;color: #fff" type="text">
              <span>更多</span><i class="el-icon-caret-bottom"></i>
            </el-button> -->
          </div>
          <div class="user-info" style="width: 100%">
            <el-form ref="queryUserForm" :model="queryParamsUser" :inline="true" label-width="80px">
              <el-row class="user-info-item">
                <el-col style="width: 33%">
                  <el-form-item label="用户编号" prop="userId">
                    <el-input v-model="queryParamsUser.userId"></el-input>
                  </el-form-item>
                </el-col>
                <el-col style="width: 33%">
                  <el-form-item label="用户名称" prop="userName" >
                    <el-input v-model="queryParamsUser.userName" readOnly></el-input>
                  </el-form-item>
                </el-col>
                <el-col style="width: 33%">
                  <el-form-item label="证件号码" prop="userCode">
                    <el-input v-model="queryParamsUser.userCode" readOnly></el-input>
                  </el-form-item>
                </el-col>

              </el-row>
              <el-row class="user-info-item">
                <el-col :span="8">
                  <el-form-item label="详细地址" prop="userAddress">
                    <el-input v-model="queryParamsUser.userAddress" readOnly></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="small" @click="handleUserQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="small" @click="resetUserQuery">重置</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-descriptions :column="3" border>
              <el-descriptions-item v-for="item in userData" :label="item.name" :key="item.id" :labelStyle="{'text-align': 'right','width':'100px'}">{{item.value}}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <i class="el-icon-s-order icon"></i><span>缴费选项</span>
            <el-button style="float: right; padding: 3px 0;color: #fff" type="text">
              <i class="el-icon-s-unfold"></i>
            </el-button>
          </div>
          <el-form ref="paymentOptionsRef" :model="paymentOptionsForm" :rules="paymentOptionRules" label-width="100px">
            <!-- <div class="form-item">
              <div class="label">票据类型：</div>
              <el-select clearable v-model="paymentOptionsForm.type" placeholder="请选择票据类型" style="width: 100%">
                <el-option value="1">发票</el-option>
              </el-select>
            </div> -->
            <div class="label">预存金额：</div>
            <el-form-item label="" prop="payMoney" label-width="0px">
              <el-input v-model="paymentOptionsForm.payMoney" placeholder="请输入预存金额" style="width: 100%"></el-input>
            </el-form-item>
            <div class="label">收款方式：</div>
            <el-form-item prop="collectWay" label-width="0px">
              <el-select clearable v-model="paymentOptionsForm.collectWay" placeholder="请选择付款方式" style="width: 100%">
                <el-option key="2" value="2" label="现金收费">现金收费</el-option>
              </el-select>
            </el-form-item>
            <el-button type="success" class="prestore-btn" @click="preSave" :disabled="userMark === 0">预存</el-button>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="7">
        <el-card class="box-card3" shadow="never">
          <div slot="header" class="clearfix">
            <i class="el-icon-s-claim icon"></i><span>今日收费汇总</span>
            <el-button style="float: right; padding: 3px 0;color: #fff" type="text" @click="getPaySummary">
              <i class="el-icon-refresh"></i>
            </el-button>
          </div>
          <div class="summary-list">
            <el-row class="summary-list-item" style="" v-for="item in summaryList" :key="item.id">
              <el-col :span="9">{{item.name}}:</el-col>
              <el-col :span="15" class="number">{{item.value}} {{item.unit}}</el-col>
            </el-row>
          </div>

        </el-card>
      </el-col>
    </el-row>
    <!-- <el-row style="width: 800px;padding: 10px">
      <el-descriptions :column="5">
        <el-descriptions-item v-for="item in descriptionList" :label="item.name" :key="item.id">
          {{item.value}} {{item.unit}}
        </el-descriptions-item>
      </el-descriptions>
    </el-row> -->
    <el-row class="box-bottom">
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane v-for="item in tabList" :label="item.name" :name="item.value" :key="item.id">
          <el-table :ref="'table'+item.id" :key="tableColumnList.length"
            border
            max-height="300"
            :data="tableData"
            @row-contextmenu="openMenu"
            style="width: 100%;background: white" >
            <el-table-column
              v-for="item in tableColumnList"
              :key="item.id"
              :prop="item.prop"
              :label="item.label"
              :width="item.width" align="center"
              show-overflow-tooltip>
              <template v-slot="scope">
                <!-- 自定义列内容 -->
                <div v-if="item.dict">
                  <dict-tag :options="dict.type[item.dict]" :value="scope.row[item.prop]"/>
                </div>
                <!-- 默认列内容 -->
                <div v-else>{{ (scope.row[item.prop] === '' || scope.row[item.prop] === null) ? '-' : scope.row[item.prop]  }}</div>
              </template>
            </el-table-column>
          </el-table>
          <!-- <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          /> -->
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <ul v-show="menuVisible" ref="menuRef" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
      <li @click="revokedPrePayment"><i class="el-icon-close"></i> 撤销</li>
    </ul>
  </div>
</template>
<script>
import {getUserInfo,getPrePaymentList,getPaySummaryToday,addPrePayment,revokedPrePayment} from "@/api/basedata/useraccount";
import {getBillListInGtsf} from "@/api/datastatistics/bill/bill";
export default {
  dicts: ['pay_type', 'collect_way','pay_status','usage_type'],
  data() {
    var checkNumber = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('预存金额不能为空'));
        }
        setTimeout(() => {
          if (!isNaN(value) && !isNaN(parseFloat(value))) {
            callback();
          } else {
            callback(new Error('请输入数字值'));
          }
        }, 200);
      };
    return {
      firstYcId:null,
      revokedRow:null,
      menuVisible:false,
      top: 0,
      left: 0,
      tableColumnList: [
        {id: 1, label: '用户编号', prop: 'userId', width: '200'},
        {id: 2, label: '年月', prop: 'readDate', width: '200'},
        {id: 3, label: '抄表时间', prop: 'createTime', width: '200'},
        {id: 4, label: '合计金额', prop: 'totalPrice', width: '140'},
        {id: 5, label: '违约金', prop: 'lateFee', width: ''},
      ],
      activeName: '1',
      paymentOptionsForm: {
        payMoney:null,
        collectWay:'2',
      },
      paymentOptionRules: {
        payMoney: [
          { required: true, message: '请输入预存金额', trigger: 'blur' },
          { validator:checkNumber, trigger: 'blur' }
        ],
        collectWay: [
          { required: true, message: '请选择收费方式', trigger: 'change' }
        ],
      },
      tabList: [
        {id: 1, name: '月结欠费',value: '1' },
        {id: 2, name: '结算记录',value: '2'},
        {id: 3, name: '预存缴费记录',value: '3'},
      ],
      tableData: [],
      summaryList: [
        {id: 1, name: '现金收费',value: 0, unit: '元'},
        {id: 2, name: '转账收费',value: 0, unit: '元'},
        {id: 3, name: '在线收费',value: 0, unit: '元'},
        {id: 4, name: '收费合计',value: 0, unit: '元'},
        {id: 5, name: '收费笔数',value: 0, unit: '笔'},
      ],
      descriptionList: [
        {id: 1, name: '表计类型',value: 'NBIoT', unit: ''},
        {id: 2, name: '口径',value: 15, unit: ''},
        {id: 3, name: '累计用量',value: 256, unit: '吨'},
        {id: 4, name: '最后抄表',value: '2025-06-18', unit: ''},
        {id: 5, name: '用户性质',value: '居民', unit: ''},
        {id: 6, name: '定价信息',value: '官方价', unit: ''},
        {id: 7, name: '综合单价',value: 1, unit: '元/吨'},
        {id: 8, name: '本年用量',value: 0, unit: '吨'},
      ],
      userData: [
        // {id: 1, name: '月结欠费:',value: '0', unit: ''},
        // {id: 2, name: '违约金:',value: '0', unit: ''},
        {id: 1, name: '欠费合计:',value: '0', unit: ''},
        // {id: 4, name: '本月费用:',value: '0', unit: ''},
        {id: 2, name: '结算余额:',value: '0', unit: ''},
        {id: 3, name: '可用余额:',value: '0', unit: ''},
      ],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
      },
      queryParamsUser: {
        userCode: null,
        userName: null,
        userId: null,
        userAddress: null,
      },
      isCheck:0,
      userMark:1,//用户在场/离场状态 1：在场 ，0：离场
    }
  },
  mounted () {
    document.addEventListener('click',this.bodyCloseMenu)
  },
  // 在页面注销前，将点击事件给移除
  beforeDestroy() {
    document.removeEventListener('click',this.bodyCloseMenu)
  },
  methods: {
    revokedPrePayment(){
      //撤销，只有预存的能撤销，而且只能撤销最后一笔预存
      revokedPrePayment({id:this.revokedRow.id}).then(response => {
        this.$modal.msgSuccess("撤销成功");
        this.handleUserQuery();
      });
      this.menuVisible = false;
    },
    bodyCloseMenu(e) {
      let self = this
      if (this.$refs.menuRef && !this.$refs.menuRef.contains(e.target)) {
        if (self.menuVisible === true) {
          self.menuVisible = false
        }
      }
    },
    openMenu(row, column, event) {
      if(this.userMark == 1 && row.payType=="1" && row.payStatus =="1" && row.id === this.firstYcId){
        const menuMinWidth = 105
        const offsetLeft = this.$el.getBoundingClientRect().left // container margin left
        const offsetWidth = this.$el.offsetWidth // container width
        const maxLeft = offsetWidth - menuMinWidth // left boundary
        const left = event.clientX - 180; // 15: margin right

        if (left > maxLeft) {
          this.left = maxLeft
        } else {
          this.left = left
        }
        this.top = event.clientY - 100;
        this.menuVisible = false;
        this.menuVisible = true;
        this.revokedRow = row;
        event.preventDefault();  // 阻止浏览器默认右键事件
      }
    },
    //预存
    preSave(){
      if(this.userMark === 1){//在场
        this.$refs['paymentOptionsRef'].validate((valid) => {
          if (valid && (this.queryParamsUser.userId != null && this.queryParamsUser.userId != '')) {
            this.paymentOptionsForm.userId = this.queryParamsUser.userId;
            addPrePayment(this.paymentOptionsForm).then(response => {
              this.paymentOptionsForm = {
                payMoney:null,
                collectWay:'2',
              };
              this.$modal.msgSuccess("预存成功");
              this.handleUserQuery();
            });
          }
        });
      }
    },
    handleTabClick() {
      this.tableColumnList = [
            {id: 1, label: '用户编号', prop: 'userId', width: '200'},
            {id: 2, label: '用量类型', prop: 'usageType', width: '150',dict:'usage_type'},
            {id: 3, label: '年月', prop: 'readDate', width: '200'},
            {id: 4, label: '抄表时间', prop: 'createTime', width: '200'},
            {id: 5, label: '合计金额', prop: 'totalPrice', width: '140'},
            {id: 6, label: '违约金', prop: 'lateFee', width: ''},
          ];
      switch (this.activeName) {
        case '1':
          this.isCheck = 0;
          this.getBill(this.queryParamsUser.userId);
          break;
        case '2':
          this.isCheck = 1;
          this.getBill(this.queryParamsUser.userId);
          break;
        case '3':
          this.tableColumnList = [
            {id: 1, label: '用户编号', prop: 'userId', width: '120'},
            {id: 2, label: '用量类型', prop: 'usageType', width: '150',dict:'usage_type'},
            {id: 3, label: '缴费类型', prop: 'payType', width: '120',dict:'pay_type'},
            {id: 4, label: '上次结余', prop: 'lastMoney', width: '150'},
            {id: 5, label: '支付金额', prop: 'payMoney', width: '150'},
            {id: 6, label: '核销月份', prop: 'checkMonth', width: '120'},
            {id: 7, label: '核销金额', prop: 'checkMoney', width: '150'},
            {id: 8, label: '本次结余', prop: 'currentMoney', width: '150'},
            {id: 8, label: '找零金额', prop: 'changeMoney', width: '150'},
            {id: 9, label: '收款方式', prop: 'collectWay', width: '120',dict:'collect_way'},
            {id: 10, label: '支付时间', prop: 'createdTime', width: '150'},
            {id: 11, label: '收费员', prop: 'nickName', width: '120'},
            {id: 12, label: '充值状态', prop: 'payStatus', width: '120',dict:'pay_status'},
            {id: 13, label: '充值说明', prop: 'payMark', width: '140'},
          ];
          this.getPrePayment(this.queryParamsUser.userId);
          break;
      }
      // this.$nextTick(() => {
      //   this.$refs['table'+this.activeName][0].doLayout();
      // });
    
    },
    getBill(userId){
      getBillListInGtsf({userId:userId,checkFlg:this.isCheck}).then(response => {
        this.tableData = response.data;
      });
    },
    getPrePayment(userId){
      getPrePaymentList({userId:userId}).then(response => {
        this.tableData = response.data;
        for(let i=0;i<this.tableData.length;i++){
          let element = this.tableData[i];
          if(element.payType === "1"){
            this.firstYcId = element.id;
            break;
          }
        }
      });
    },
    handleUserQuery() {
      this.getUserInfoByUserId(this.queryParamsUser.userId);
    },
    getUserInfoByUserId(userId){
      this.resetUser(userId);
      getUserInfo(userId).then(response => {
        let dd = response.data;
        this.queryParamsUser = {
          userCode: dd.userCode,
          userName: dd.userName,
          userId: dd.userId,
          userAddress: dd.userAddress,
        }
        // this.userData[0].value = dd.monthArrear;
        // this.userData[1].value = dd.lateFee;
        this.userData[0].value = dd.totalArrear;
        // this.userData[3].value = dd.monthCost;
        this.userData[1].value = dd.settleBalance;
        this.userData[2].value = dd.availableBalance;
        this.handleTabClick();
        this.getPaySummary();
        
        this.userMark = dd.userMark;
        //用户离场提示
        if(dd.userMark === 0){
          this.$modal.alertWarning("该用户已离场，请录入其他用户！");
        }
      });
    },
    getPaySummary(){
      getPaySummaryToday({userId:this.queryParamsUser.userId}).then(response => {
        let dd = response.data;
        this.summaryList[0].value = dd.pay2;
        this.summaryList[1].value = dd.pay3;
        this.summaryList[2].value = dd.pay4;
        this.summaryList[3].value = dd.total;
        this.summaryList[4].value = dd.count;
      });
    },
    resetUser(userId){
      this.queryParamsUser = { userCode: null, userName: null, userId: userId, userAddress: null };
      this.userData[0].value = 0;
      this.userData[1].value = 0;
      this.userData[2].value = 0;
      // this.userData[3].value = 0;
      // this.userData[4].value = 0;
      // this.userData[5].value = 0;
      this.tableData = [];
    },
    resetUserQuery() {
      this.resetForm("queryUserForm");
      // this.handleQuery("queryUserForm");
      this.resetUser(null);
      //清空下方月结欠费，结算记录，预存缴费记录查询数据
    }
  },

}
</script>
<style lang="scss" scoped>
::v-deep .el-card{
  border-radius: 0;
}
::v-deep .el-card__header{
  background: linear-gradient(to right, #004687, #4682B4);
  color: #fff;
  font-size: 14px;
  padding: 10px 15px;
}
.box-card1{
  height: 300px;
  .user-info{
    border: 1px solid #ddd;
    .user-info-item{
      border-bottom: 1px solid #ddd;
      padding: 0 5px;
      ::v-deep .el-form-item {
        margin: 10px 0;
      }
    }
  }
}
.box-card{
  height: 300px;
}
.icon{
  font-size: 20px;
  margin-right: 5px;
}
.label{
  padding: 10px 0 5px 0px;
  //font-size: 14px;
}
.prestore-btn{
  border-radius: 0;
  width: 100%;
}
.box-card3{
  height: 300px;
  .summary-list{
    border: 1px solid #ddd;

    .summary-list-item{
      padding: 10px;
      text-align: right;
      border-bottom: 1px solid #ddd;
      margin-bottom: -1px;
      .number{
        font-weight: bold;
      }
    }
  }
}
.box-bottom{
  height: calc(100% - 310px) !important;
  max-width: 1946px;
  min-width:1100px;
  overflow: auto;
  padding: 5px;
  ::v-deep .el-tabs--border-card > .el-tabs__header{
    background: linear-gradient(to right, #004687, #4682B4);
  }
  ::v-deep .el-tabs--border-card{
    box-shadow: none;
  }
  ::v-deep .el-tabs__item{
    color: white;
  }
  ::v-deep .el-tabs__item .is-top .is-active{
    color: #1c84c6;
  }
  ::v-deep .el-tabs__content{
    padding: 0;
  }
}
.contextmenu {
  margin: 0;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, .3);
  li {
    margin: 0;
    padding: 7px 16px;
    cursor: pointer;
    &:hover {
      background: #eee;
    }
  }
}
</style>
